package com.cg.demo.aop;

import com.cg.demo.annotation.HasRole;
import server.request.HttpRequest;
import spring.RequestContext;
import spring.annotation.bean.Component;
import spring.aop.ProceedingJoinPoint;
import spring.aop.annotation.Aspect;
import spring.aop.annotation.Before;
import spring.aop.annotation.PointCut;

import java.lang.reflect.Method;

/**
 * @author cg
 * @date 2023/6/22 13:13
 */
@Aspect
@Component
public class HasRoleAspect {
    @PointCut("annotation:com.cg.demo.annotation.HasRole")
    public void pointcut() {

    }

    @Before
    public void before(ProceedingJoinPoint joinPoint) {
        Method method = joinPoint.getMethod();
        HasRole hasRole = method.getAnnotation(HasRole.class);
        if (hasRole == null) return;
        HttpRequest request = (HttpRequest) RequestContext.getHttpRequest();
        String username = request.getCookie("username");
        if (!hasRole.value().equals(username)) {
            throw new RuntimeException("权限不够");
        }
    }
}
